package cn.itcast.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * className: TestThreadSafe
 * description:
 * date: 2023/2/13-16:40
 * <p>
 * project: concurrent
 * package: cn.itcast.n4
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Slf4j(topic = "c.TestThreadSafe")
public class TestThreadSafe {
    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 200;

    public static void main(String[] args) {
        ThreadUnsafe test = new ThreadUnsafe();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + (i + 1)).start();
        }
    }
}

class ThreadUnsafe {
    ArrayList<String> list = new ArrayList<>();

    public void method1(int loopNumber) {
        for (int i = 0; i < loopNumber; i++) {
            method2();
            method3();
        }
    }

    public void method3() {
        list.remove("0");
    }

    public void method2() {
        list.add("1");
    }
}

class ThreadSafe {

    public void method1(int loopNumber) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }

    private void method3(ArrayList<String> list) {
        list.remove("0");
    }

    private void method2(ArrayList<String> list) {
        list.add("1");
    }
}

class ThreadSafeSubClass extends ThreadSafe {
    //    @Override
    public void method3(ArrayList<String> list) {
        System.out.println(2);
        new Thread(() -> {
            list.remove(0);
        }).start();
    }
}